<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="750px"
    :before-close="close"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-scrollbar v-loading="loading" max-height="calc(100vh - 350px)">
      <div style="width: 98%">
        <CustomForm
          ref="formRef"
          :formData="formData"
          :schemas="formSchemas"
          :rules="rules"
          :show-span="true"
          :label-width="120"
          size="default"
        />
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="submit">
          暂存
        </el-button>
        <el-button
          type="success"
          :loading="submitLoading"
          @click="submit('submit')"
        >
          提交
        </el-button>
      </div>
    </template>
    <SelectApprovePerson
      ref="selectApprovePerson"
      @submit="handleSelectPersonSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, h, reactive, ref, toRaw, useTemplateRef } from 'vue'
import {
  getCoordinationApplicationDetailById,
  ICoordinationApplicationDetail,
  saveOrUpdateCoordinationApplication,
  submitCoordinationApplication,
} from '@/api/application/coordination'
import useFetch from '@/hooks/useFetch'
import CustomForm from '@/components/form/CustomForm.vue'
import useUserStore from '@/stores/user'
import { IFormSchemas } from '@/type/table'
import UnitSelect from '@/components/unit/UnitSelect.vue'
import { FormRules } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import dayjs from 'dayjs'
import SelectApprovePerson from '@/components/approve/SelectApprovePerson.vue'
import { getFileIdStr, initIFileList } from '@/plugins/file'
import { Message } from '@/hooks/message'
import { ESelectApproveUserType } from '@/api/sys/userManage'

const userStore = useUserStore()

const formRef = useTemplateRef<typeof CustomForm>('formRef')
const selectApprovePerson = useTemplateRef<typeof SelectApprovePerson>(
  'selectApprovePerson',
)

const emits = defineEmits(['update'])

const defaultData = {
  matterTitle: undefined,
  applyTopic: '',
  applyUnitId: userStore.unitId,
  applyUserId: userStore.id,
  applyUserName: userStore.userName,
  applyUnitName: userStore.unitName,
  applyTime: dayjs().format('YYYY-MM-DD'),
  coordinationDeptId: [],
  applyReason: '',
  matterId: undefined,
  audioDataVos: undefined,
  approveUserId: undefined,
}

const copyDefaultData = cloneDeep(defaultData)

const formData = reactive<ICoordinationApplicationDetail>(defaultData)

const rules = reactive<FormRules<ICoordinationApplicationDetail>>({
  applyTopic: [{ required: true, message: '请输入协调标题', trigger: 'blur' }],
  applyReason: [{ required: true, message: '请输入协调内容', trigger: 'blur' }],
  coordinationDeptId: [
    { required: true, message: '请选择协调部门', trigger: 'change' },
  ],
  audioDataVos: [
    { required: true, message: '请上传相关材料', trigger: 'blur' },
  ],
})
const detailId = ref(undefined)

const formSchemas = computed<IFormSchemas[]>(() => {
  return [
    {
      label: '协调标题',
      prop: 'applyTopic',
      type: 'input',
      placeholder: '请输入协调标题',
      componentProps: {
        maxlength: 50,
        clearable: true,
      },
    },
    {
      label: '申请时间',
      prop: 'applyTime',
      type: 'input',
      disabled: true,
    },

    {
      label: '申请部门',
      prop: 'applyUnitName',
      type: 'input',
      disabled: true,
    },
    {
      label: '申请人',
      prop: 'applyUserName',
      type: 'input',
      disabled: true,
    },

    {
      label: '协调内容',
      prop: 'applyReason',
      type: 'input',
      placeholder: '请输入协调内容',
      componentProps: {
        type: 'textarea',
        maxlength: 500,
        clearable: true,
        autosize: { minRows: 4, maxRows: 8 },
        'show-word-limit': true,
      },
    },
    {
      label: '协调部门',
      prop: 'coordinationDeptId',
      type: (props) => {
        return h(UnitSelect, {
          ...props,
          clearable: true,
          multiple: true,
          placeholder: '请选择协调部门',
          'collapse-tags': true,
          'collapse-tags-tooltip': true,
          'max-collapse-tags': 3,
        })
      },
    },
    {
      label: '相关材料',
      prop: 'audioDataVos',
      type: 'upload',
      limit: 10,
    },
  ]
})

const { loading, execute, onFetchSuccess } =
  useFetch<ICoordinationApplicationDetail>(getCoordinationApplicationDetailById)

onFetchSuccess((data: ICoordinationApplicationDetail) => {
  data.coordinationDeptId = (data.coordinationDeptId as string)
    ?.split(',')
    .map((item) => Number(item))
  const newAudioDataVos = initIFileList(data.audioDataVos)
  delete data.audioDataVos
  Object.assign(formData, {
    ...data,
  })
  formData.audioDataVos = newAudioDataVos
})

const {
  loading: saveLoading,
  execute: saveExecute,
  onFetchSuccess: saveOnFetchSuccess,
} = useFetch(saveOrUpdateCoordinationApplication)

saveOnFetchSuccess(() => {
  success('暂存成功')
})

const {
  loading: submitLoading,
  execute: submitExecute,
  onFetchSuccess: submitOnFetchSuccess,
} = useFetch(submitCoordinationApplication)

submitOnFetchSuccess(() => {
  success()
})

function success(message = '提交成功') {
  emits('update')
  close()
  Message({
    message: message,
    type: 'success',
  })
}

const dialogVisible = ref(false)

defineExpose({ show })

const dialogTitle = computed(() => {
  return detailId.value ? '编辑协调申请' : '新增协调申请'
})

/**
 * @param matterId 关联事项id
 * @param id 协调申请id
 */
async function show(matterId?: number, id?: number) {
  dialogVisible.value = true
  if (id) {
    detailId.value = id
    await execute(id)
  } else {
    // 新增
    Object.assign(formData, { matterId })
  }
}

function close() {
  dialogVisible.value = false
  Object.assign(formData, copyDefaultData)
  formRef.value?.reset()
  detailId.value = undefined
}

// 提交
async function submit(type = 'save') {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      if (type === 'submit') {
        selectApprovePerson.value?.show({
          type: ESelectApproveUserType.COORDINATION,
          applyId: detailId.value,
        })
      } else {
        saveOrSubmit()
      }
    }
  })
}

// 保存或提交
async function saveOrSubmit(type = 'save', approveUserId?: number) {
  const originData = toRaw(formData)
  const postData = {
    ...originData,
    coordinationDeptId: (originData.coordinationDeptId as number[]).join(','),
    id: detailId?.value ?? undefined,
    applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    approveUserId: approveUserId
      ? approveUserId
      : (originData?.approveUserId ?? undefined),
    fileIdStr: getFileIdStr(originData.audioDataVos),
  }
  delete postData.audioDataVos
  type === 'submit'
    ? await submitExecute(postData)
    : await saveExecute(postData)
}

function handleSelectPersonSuccess(approveUserId: number) {
  saveOrSubmit('submit', approveUserId)
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-date-editor--date) {
  --el-date-editor-width: 190px;
  margin-right: 16px;
}
</style>
